<template>
  <el-dialog title="编辑"  :close-on-click-modal="false" :visible.sync="show" 
  class="dialog_index dialog_image" :before-close="cancle">
    <el-form v-loading="loading" :rules="rules" ref="form" :model="form">
      <el-form-item label="产品型号名称：" prop="product_model_name" >
        <el-select  v-model="form.product_model_name" placeholder="产品型号名称（必填项）" filterable clearable  
        @focus="getProductModelNameList"  @change="changeProductModelName">
          <el-option v-for="item in productModelNameList" :key="item.id" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="站点：" prop="site">
        <el-select  v-model="form.site" placeholder="站点 （必填项）"  clearable  @focus="getSiteList" @change="changeSite()" >
          <el-option v-for="item in siteList" :key="item.id" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="ASIN：" prop="asin">
        <el-input v-model="form.asin " placeholder="ASIN（非必填项）"></el-input>
      </el-form-item>
      <el-form-item label="评论用户名：" prop="comment_username">
        <el-input v-model="form.comment_username " placeholder="评论用户名（必填项）"></el-input>
      </el-form-item>
      <el-form-item label="评论标题：" prop="comment_title">
        <el-input v-model="form.comment_title " placeholder="评论标题（必填项）"></el-input>
      </el-form-item>
      <el-form-item label="评论内容：" prop="comment_content">
        <el-input v-model="form.comment_content " placeholder="评论内容 （必填项）"></el-input>
      </el-form-item>
      <el-form-item label="评论星级：" prop="comment_star">
        <el-select  v-model="form.comment_star" placeholder="评论星级（必填项）" clearable   >
          <el-option v-for="item in commentStarList" :key="item.label" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="产品属性：" prop="attributes">
        <el-select  v-model="form.attributes" placeholder="产品属性（必填项）" clearable  @focus="getAttributesList()">
          <el-option v-for="item in attributesList" :key="item.label" :value="item.value" :label="item.label"></el-option>
        </el-select>
      </el-form-item>
      <el-form-item label="Amazon评论链接：" prop="amazon_review_link">
        <el-input v-model="form.amazon_review_link " placeholder="Amazon评论链接（非必填项）"></el-input>
      </el-form-item>
      <el-form-item label="评论日期：" class="commentTime" prop="comment_time">
     <el-date-picker  v-model="form.comment_time"  format="yyyy-MM-dd"     type="date"
      value-format="yyyy-MM-dd HH:mm:ss" placeholder="评论日期 （必填项）"></el-date-picker>      </el-form-item> 
      <el-form-item label="评论图片：" class="amazonLink">
          <el-upload class="upload-banner imgReview" action="/api/api/general/upload"  multiple
          :on-success="(response, file, fileList) => handleBannerSuccess(response, file, fileList, item)"
            :on-error="handleBannerError" :before-upload="beforeBannerUpload"
          :show-file-list="false" accept=".jpg,.jpeg,.png " :data="{type:'product_comment', imageheight: imgH, imagewidth: imgW}" >
            <br><el-button size="small" type="primary" @click="closeDrawerDialog">图库选择</el-button> 
            <el-button slot="trigger" size="small" type="primary">本地上传</el-button>
          </el-upload>
          <div class="imgReview" v-for="(image, idx) in form.comment_image" :key="image">
            <el-image :src="utils.setCdnUrl() + image"></el-image>
            <el-button class="del" @click="delImage(idx)">删除</el-button>
          </div>
      </el-form-item>
    
    </el-form>
    <span slot="footer" class="dialog-footer">
      <el-button type="search" @click="submitForm">保存</el-button>
      <el-button @click="cancle">取消</el-button>
    </span>
    <Drawer v-show="showDrawer" :isMulti="true" :type="'product_comment'" :show="showDrawer"  @closeDialog="closeDrawerDialog"></Drawer>

    </el-dialog>
</template>

<script>
import Drawer  from '@/components/Gallery/index.vue' 
import { productModelNameList } from '@/api/product/productBasic.js'
import {  siteSiteList } from '@/api/manage/site.js'
import { productCommentGet,  productCommentPost, productAttrList} from '@/api/product/productComment.js'

export default {
  data () {
    return {
      loading: false,
      productModelNameList:[],
      siteList: [],
      form: {
        product_model_name:'',
        site: '',
        asin: '',
        comment_username: '',
        comment_title: '',
        comment_star: '',
        comment_content: '',
        attributes: '',
        amazon_review_link: '',
        comment_image: [],
        comment_time: '',
        site_id: '',
        product_name: ''
      },
      commentStarList: [
        {value: '5', label: '5星'},
        {value: '4', label: '4星'},
        {value: '3', label: '3星'},
        {value: '2', label: '2星'},
        {value: '1', label: '1星'},
      ],
      attributesList:[],
      imgH: '',
      imgW: '',
      rules: {
        amazon_review_link:[],
        asin: [],
        product_model_name: [
          { required: true, message: '字段产品型号名称为必填项！ ', trigger: 'change' }
        ],
        site: [
          { required: true, message: '字段站点为必填项！ ', trigger: 'change' }
        ],
        comment_username:[
          { required: true, message: '字段评论用户名为必填项！ ', trigger: 'blur' }
        ],
        comment_title: [
          { required: true, message: '字段评论标题为必填项！ ', trigger: 'blur' },
          { max: 100, message: '字段评论标题最多100字符！ ', trigger: 'blur' }
        ],
        comment_content: [
          { required: true, message: '字段评论内容为必填项！ ', trigger: 'blur' },
        ],
        comment_star: [
          { required: true, message: '字段评论星级为必填项！ ', trigger: 'change' }
        ],
        attributes: [
          { required: true, message: '字段产品属性为必填项！ ', trigger: 'blur' }
        ],
        comment_time: [
          { required: true, message: '字段评论日期为必填项！ ', trigger: 'change' }
        ]

      },
      showDrawer: false
    }
  },
  components: { Drawer },
  props: {
    show: Boolean,
    closeDialog:Function,
    id: Number
  },
  watch: {
    show: function(){
      if(this.show){
        this.getProductComment()
      }
    }
  },
  methods: {
    // 图库选择是否显示
    closeDrawerDialog (data) {
      this.showDrawer = !this.showDrawer
      if (data && data.length > 0) { 
        for(let i = 0; i < data.length; i++) {
          if(data[i].filesize / 1024 < 1024 && data[i].imagetype == ('png' || 'jpg' || 'jpeg')) {
            this.form.comment_image.push(data[i].url)
          } else {
            this.$message.error("只能上传≤1M的.png/.jpg/.jpeg格式的图片；图片"+ data[i].filename +'不符合要求')
          }

        }
      }
    },
    delImage (index) {
      this.form.comment_image.splice(index, 1)
    },
    getProductComment () {
      let params = {
        id: this.id
      }
      productCommentGet(params).then(res=>{
        if(res.state == 1){
          let  data = res.data
          this.form = data
          if (data.comment_image) {
            this.form.comment_image = data.comment_image.split(',')
          }else {
            this.form.comment_image = []
          }
        }
      })
    },
    changeProductModelName () {
      this.form.site = ''
      this.form.site_id = ''
      this.form.attributes = ''
    },
    changeSite () {
      let list = this.siteList
      for(let i =0 ;i < list.length; i++){
        if(list[i].value == this.form.site){
          this.form.site_id = list[i].id
        }
      }
      this.form.attributes = ''
    },

    getSiteList(){ //站点
      siteSiteList().then(res=>{
        this.siteList = res.data
      })
    },
    getProductModelNameList () {
      productModelNameList().then(res=>{
        if(res.state == 1){
          this.productModelNameList = res.data
        }
      })
    },
    getAttributesList () {
      if(this.form.product_model_name && this.form.site){
        this.getProductAttrList()
      }else {
        this.$message.error('未选择产品名称+站点，不可选择产品属性')
      }
    },
    getProductAttrList () {
      let params = {
        site_id: this.form.site_id,
        product_model_name: this.form.product_model_name
      }
      productAttrList(params).then(res=>{
        if (res.state == 1){
          this.attributesList= res.data
        }
      })
    },
    
    cancle () {
      this.$emit('closeDialog')
      this.$refs.form.resetFields()
    },
    submitForm () {
      this.$refs.form.validate((valid) => {
        if (valid) {
          this.update()
        } else {
          return false;
        }
      })
    },
 
    update () {
      let params = this.form 
      productCommentPost(params).then(res=>{
        if(res.state == 1){
          this.$message.success('保存成功')
          this.cancle()
        }
      })
    },
    handleBannerSuccess (response) {
      this.form.comment_image.push(response.data.filePathName)
      this.$message.success('上传图片成功')   
    },
    
    handleBannerError(){
      this.$message.error('上传图标失败')   
    },
    beforeBannerUpload(file){
      let that = this
      if(file.type !== 'image/jpeg' && file.type !== 'image/jpg' &&  file.type !== 'image/png'){
        this.$message.error("仅支持.jpg/.jpeg/.png格式的图片")
        return false
      }
       const isSize = new Promise(function(resolve, reject){
        let _URL = window.URL || window.webkitURL;
        let img = new Image();
        img.onload = function() {
          console.log(img.width,img.height)
          // let valid = img.width == '1920' &&   img.height == '937' ;
          let valid = true
          valid ? resolve() : reject();
          that.imgW = img.width
          that.imgH = img.height
        }
        img.src = _URL.createObjectURL(file);
      }).then(()=>{

        return file
      }, ()=>{
        // that.$message.error('上传图标尺寸为1920*937px')
        return Promise.reject()
      })
      return isSize
    },
  
  }

}
</script>

<style>

</style>